package com.example.demo.impl;

import com.example.demo.dao.AccountWalletMapper;
import com.example.demo.model.AccountWallet;
import com.example.demo.model.User;
import com.example.demo.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class TestServiceImpl implements TestService {
    @Autowired
    AccountWalletMapper accountWalletMapper;

    @Override
    public AccountWallet selectByOpenId(String openId) {
        return accountWalletMapper.selectByOpenId(openId);
    }

    @Override
    public int updateAccountWallet(AccountWallet record) {
        return accountWalletMapper.updateAccountWallet(record);
    }

    @Override
    public List<User> initUsers() {
        List<User> res = new ArrayList<>();
        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setUserName(i + "");
            user.setAmount((String.valueOf(random.nextInt(10) * 5)));//随机指定用户存取的金额
            user.setOpenId("1");
            res.add(user);
            user.setOpenType(random.nextBoolean());//随机指定用户是存还是取
        }

        return res;
    }

    @Override
    public void process(User user) throws InterruptedException {
        //用户开始操作时间
        long startTime = System.currentTimeMillis();
        Boolean success = false;
        String message = "";
        //while时间内会不断尝试更新直到成功
        while ((startTime + 35000L) >= System.currentTimeMillis()) {
            AccountWallet accountWallet = selectByOpenId("1");
            //cash为用户要存入或取出的金额
            BigDecimal cash = BigDecimal.valueOf(Double.parseDouble(user.getAmount()));
            cash.doubleValue();
            cash.floatValue();
            String add = "+";//+表示存入，-表示取出
            BigDecimal original = accountWallet.getUserAmount();
            if (user.getOpenType()) {
                accountWallet.setUserAmount(accountWallet.getUserAmount().add(cash));
            } else {
                add = "-";
                accountWallet.setUserAmount(accountWallet.getUserAmount().subtract(cash));
            }

            //尝试更新数据库
            int res = updateAccountWallet(accountWallet);
            if (res == 1) {
                success = true;
                message = "成功" + " 基数： " + original + add + cash + " 更新后：" + accountWallet.getUserAmount();
                break;
            }

            //休息后再次尝试更新
            Thread.sleep(10L);
        }
        if (success) {
            System.out.println(message);
        } else {
            System.out.println("失败！");
        }

    }
}
